package cn.uncode.springcloud.gateway.filter;

import java.util.Arrays;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import cn.uncode.springcloud.gateway.canary.CanaryStrategy;
import cn.uncode.springcloud.gateway.ribbon.RibbonContext;
import cn.uncode.springcloud.gateway.ribbon.RibbonContextHolder;

import reactor.core.publisher.Mono;

/**
 * 灰度
 * 
 */
@Component
public class CanaryFilter implements GlobalFilter, Ordered {
	
    @Value("${info.canary.enabled:false}")
    private boolean canary;
    
    @Autowired
    private CanaryStrategy canaryStrategy;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    	if(canary) {
    		ServerHttpRequest  request = exchange.getRequest();
    		RibbonContext ribbonContext = canaryStrategy.resolve(request);
			RibbonContextHolder.setRibbonContext(ribbonContext);
			request.getHeaders().add(CanaryStrategy.FEIGN_CANARY_HEAD_KEY, ribbonContext.toString());
    	}
        return chain.filter(exchange);
    }
	
    @Override
    public int getOrder() {
        return -400;
    }
    
    private void resoveString(String str, Set<String> target) {
		if(StringUtils.isNotBlank(str)) {
			String[] item = str.split(",");
			target.addAll(Arrays.asList(item));
		}
	}
}
